//
//  RegisterViewController.m
//  CheekiOS
//
//  Created by mac on 2017/5/11.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "RegisterViewController.h"
#import "RegisterInfoViewController.h"
#import "EVTPhoneAreaCodeViewController.h"
@interface RegisterViewController (){
    int  leftTime;
    NSTimer  * countDownTimer;
}
@property (nonatomic, strong) UITextField *phoneTextField;//手机

@property (nonatomic, strong) UITextField *codeTextField;//验证码

@property (nonatomic, strong) UITextField *passwordTextField;//密码

@property (nonatomic, strong) UIButton *codeButton;

@property (nonatomic, strong) UIButton *registerButton;

@property (nonatomic, strong) NSString *code;

@property (nonatomic, strong) UIButton  *regionBtn;
@property (nonatomic, strong) NSString  *regionStr;
@property (nonatomic, strong) UILabel   *numberLab;
@property (nonatomic, strong) NSString  *numberStr;
@end

@implementation RegisterViewController

-(void)viewWillAppear:(BOOL)animated{
    [self setNavgationBarHiddenNo];
}


-(void)viewWillDisappear:(BOOL)animated{
    [self setNavgationBarHidden];
}


- (void)viewDidLoad {

    [super viewDidLoad];
    
    [self.navigationItem setTitle:@"手机号注册"];
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor blackColor], NSFontAttributeName : [UIFont systemFontOfSize:18]};

    self.view.backgroundColor = [UIColor whiteColor];
    [self selfTitleFontColor];
    
    [self configureUI];

}

- (void)configureUI {
    
    
    
    _regionStr = @"中国";
    _numberStr = @"86";
    
    UILabel *regionLab = [[UILabel alloc] init];
    regionLab.text = @"国家和地区";
    regionLab.font = FontBold(16);
    regionLab.textAlignment = NSTextAlignmentLeft;
    regionLab.textColor = [UIColor blackColor];
    [self.view addSubview:regionLab];
    [regionLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(19);
        make.top.equalTo(self.view).offset(0);
        make.height.mas_equalTo(55);
        make.width.mas_equalTo(KScreenWidth/2-19);
    }];
    
    
    _regionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_regionBtn setTitle:_regionStr forState:UIControlStateNormal];
    _regionBtn.titleLabel.font = FontBold(16);
    _regionBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [_regionBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_regionBtn addTarget:self action:@selector(regionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_regionBtn];
    
    [_regionBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(regionLab.mas_right).offset(0);
        make.top.equalTo(self.view).offset(0);
        make.height.mas_equalTo(55);
        make.width.mas_equalTo(KScreenWidth/2-33);
    }];
    
    
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.image = [UIImage imageNamed:@"jiantou2"];
    [self.view addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_regionBtn.mas_right).offset(0);
        make.top.equalTo(self.view).offset(21);
        make.height.mas_equalTo(14);
        make.width.mas_equalTo(14);
    }];
    
    UIView *linView = [[UIView alloc] init];
    linView.backgroundColor = RGB(242, 244, 244);
    [self.view addSubview:linView];
    [linView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(0);
        make.top.equalTo(regionLab.mas_bottom).offset(1);
        make.height.mas_equalTo(1);
        make.width.mas_equalTo(KScreenWidth);
    }];
    
    
    _numberLab = [[UILabel alloc]init];
    NSMutableAttributedString *messageStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"+ %@",_numberStr] attributes:nil];
    [messageStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,messageStr.length)];
    [messageStr addAttribute:NSFontAttributeName value:FontBold(13) range:NSMakeRange(0,1)];
    [messageStr addAttribute:NSFontAttributeName value:FontBold(16) range:NSMakeRange(1, messageStr.length-1)];
    self.numberLab.attributedText = messageStr;
    
    self.numberLab.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.numberLab];
    [_numberLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(13);
        make.top.equalTo(linView).offset(1);
        make.height.mas_equalTo(45);
        make.width.mas_equalTo(55);
    }];
    
    
    
    _phoneTextField = [[UITextField alloc] init];
    _phoneTextField.placeholder = @"请输入手机号";
    _phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    [_phoneTextField addTarget:self action:@selector(valueChange) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:_phoneTextField];
    [_phoneTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.numberLab.mas_right).offset(15);
        make.right.equalTo(self.view).offset(0);
        make.top.equalTo(linView).offset(1);
        make.height.mas_equalTo(45);
    }];
    
    UILabel *line1 = [[UILabel alloc] init];
    line1.backgroundColor = TheLinColor;
    [self.view addSubview:line1];
    [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(0);
        make.right.equalTo(self.view).offset(0);
        make.height.mas_equalTo(1);
        make.top.equalTo(_phoneTextField.mas_bottom).offset(1);
    }];
    
    
    _codeButton = [[UIButton alloc] init];
    [_codeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    _codeButton.backgroundColor = Colorbackground;
    _codeButton.layer.cornerRadius =12;
    _codeButton.layer.masksToBounds = YES;
    _codeButton.titleLabel.font = FontP(16);

    [_codeButton addTarget:self action:@selector(clickCodeButton) forControlEvents:UIControlEventTouchUpInside];
    [_codeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:_codeButton];
    [_codeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-5);
        make.top.equalTo(_numberLab.mas_bottom).offset(11);
        make.height.mas_equalTo(35);
        make.width.mas_equalTo(100);
    }];
    UILabel *codeLab = [[UILabel alloc] init];
    codeLab.text = @"验证码";
    codeLab.font = FontBold(16);
    codeLab.textColor = [UIColor blackColor];
    [self.view addSubview:codeLab];
    [codeLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(19);
        make.top.equalTo(_numberLab.mas_bottom).offset(5);
        make.height.mas_equalTo(45);
        make.width.mas_equalTo(55);
    }];
    
    _codeTextField = [[UITextField alloc] init];
    _codeTextField.placeholder = @"请输入验证码";
    _codeTextField.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:_codeTextField];
    [_codeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(codeLab.mas_right).offset(6);
        make.top.equalTo(_numberLab.mas_bottom).offset(5);
        make.height.equalTo(_phoneTextField.mas_height);
        make.right.equalTo(_codeButton.mas_left).offset(13);
        
    }];
    UILabel *line2 = [[UILabel alloc] init];
    line2.backgroundColor = TheLinColor;
    [self.view addSubview:line2];
    [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(0);
        make.right.equalTo(self.view).offset(0);
        make.height.mas_equalTo(1);
        make.top.equalTo(_codeTextField.mas_bottom).offset(5);
    }];
    
    
    UILabel *passwordLab = [[UILabel alloc] init];
    passwordLab.text = @"密码";
    passwordLab.font = FontBold(16);
    passwordLab.textColor = [UIColor blackColor];
    [self.view addSubview:passwordLab];
    [passwordLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(19);
        make.width.mas_equalTo(55);
        make.height.mas_equalTo(45);
        make.top.equalTo(codeLab.mas_bottom).offset(13);
    }];
    
    
    _passwordTextField = [[UITextField alloc] init];
    _passwordTextField.placeholder = @"请输入6-16位密码";
    _passwordTextField.secureTextEntry = YES;
    [self.view addSubview:_passwordTextField];
    [_passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(passwordLab.mas_right).offset(6);
        make.right.equalTo(self.view).offset(10);
        make.height.mas_equalTo(45);
        make.top.equalTo(_codeTextField.mas_bottom).offset(13);
    }];
    
    
    UILabel *line3 = [[UILabel alloc] init];
    line3.backgroundColor = RGB(242, 244, 244);
    [self.view addSubview:line3];
    [line3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(0);
        make.right.equalTo(self.view).offset(0);
        make.height.mas_equalTo(1);
        make.top.equalTo(_passwordTextField.mas_bottom).offset(5);
    }];
    _registerButton = [[UIButton alloc] init];
//    _registerButton.layer.cornerRadius = 25;
//    _registerButton.layer.shadowColor = RGB(254, 240, 178).CGColor;
//    _registerButton.layer.shadowOffset = CGSizeMake(8.0f, 8.0f);
//    _registerButton.layer.shadowOpacity = 0.6f;
//    _registerButton.layer.shadowRadius=5;
    _registerButton.layer.cornerRadius = 9;
    
    _registerButton.layer.masksToBounds = YES;
    _registerButton.backgroundColor = Colorbackground;
    [_registerButton setTitle:@"确认注册" forState:UIControlStateNormal];
    [_registerButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.view addSubview:_registerButton];
    [_registerButton addTarget:self action:@selector(clickRegisterButton) forControlEvents:UIControlEventTouchUpInside];
    [_registerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(35);
        make.right.equalTo(self.view).offset (-35);
        make.top.equalTo(line3.mas_bottom).offset(150);
        make.height.mas_equalTo(50);
    }];
}
- (void)clickPhotoButton {
    

    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"请输入正确的手机号码" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertVC addAction:confirAction];
    [self.navigationController presentViewController:alertVC animated:YES completion:nil];
    
    
}

- (void)passwordTextFieldButton {
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"请输入六位以上密码" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertVC addAction:confirAction];
    [self.navigationController presentViewController:alertVC animated:YES completion:nil];
    
    
}

- (void)codeTextFieldbutton{
    

    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"请输入正确的验证码" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertVC addAction:confirAction];
    [self.navigationController presentViewController:alertVC animated:YES completion:nil];
    
}

- (void)clickRegisterButton {
    [self.view endEditing:YES];
    _registerButton.enabled = NO;
    if (_phoneTextField.text.length == 0||_phoneTextField.text.length != 11) {
        
        [self clickPhotoButton];
        _registerButton.enabled = YES;
        return ;
    }
    if (_passwordTextField.text.length < 6) {
        [self passwordTextFieldButton];
        _registerButton.enabled = YES;
        return ;
    }
    if (![_codeTextField.text isEqualToString:_code]||!_codeTextField.text.length) {
        [self codeTextFieldbutton];
        _registerButton.enabled = YES;
        return ;
    }
    [SVProgressHUD show];
    //注册
    [HQHttpManager registerWithAccout:_phoneTextField.text password:_passwordTextField.text successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
        _registerButton.enabled = YES;
        [SVProgressHUD dismiss];
        if (isSuccess) {
            [defaults removeObjectForKey:@"perfectloginName"];
            [defaults removeObjectForKey:@"perfectloginBirthday"];
            [defaults synchronize];
            
            
            //完善资料
            NSString* identifierNumber = [[UIDevice currentDevice].identifierForVendor UUIDString] ;
            NSLog(@"手机序列号: %@",identifierNumber);
            
        
            [HQHttpManager userLoginWithAccout:_phoneTextField.text password:_passwordTextField.text thirdNO:nil thirdType:nil mode:@"mobile" nickName:nil deviceNo:identifierNumber successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
                [SVProgressHUD dismiss];
                

                RegisterInfoViewController *vc = [[RegisterInfoViewController alloc] init];
                vc.LoginType = @"1";
                
                [self.navigationController pushViewController:vc animated:YES];

            }];
        }
    }];
}

- (void)clickCodeButton {
    _codeButton.enabled = NO;

    if (_phoneTextField.text.length == 0||_phoneTextField.text.length != 11) {
        [self clickPhotoButton];
        _codeButton.enabled = YES;
        return;
    }
    [HQHttpManager getCodeWithAccout:_phoneTextField.text type:@"reg" successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
        if (isSuccess) {
            _code = resultDic[@"code"];
            [self fireCountDownTimer];
        } else {
            _codeButton.enabled = YES;
        }
    }];
}


- (void)fireCountDownTimer {
    [self stopTimer];
    [_codeButton setTitle:@"60s" forState:UIControlStateNormal];
    _codeButton.backgroundColor = [UIColor lightGrayColor];
    leftTime = 60;
    countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1
                                                      target:self
                                                    selector:@selector(countDownAction)
                                                    userInfo:nil
                                                     repeats:YES];
}

- (void)stopTimer {
    if (countDownTimer || [countDownTimer isValid]) {
        [countDownTimer invalidate];
        countDownTimer = nil;
    }
}

- (void)countDownAction {
    leftTime --;
    if (leftTime < 1) {
        [self stopTimer];
        leftTime = 0;
        _codeButton.enabled = YES;
        [_codeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        _codeButton.backgroundColor = ColorI(0xffeb8e);
    } else {
        _codeButton.backgroundColor = [UIColor lightGrayColor];
        [_codeButton setTitle:[NSString stringWithFormat:@"%ds",leftTime] forState:UIControlStateNormal];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)valueChange {
    if (_phoneTextField.text.length>11) {
        _phoneTextField.text = [_phoneTextField.text substringToIndex:11];
        [self clickPhotoButton];
    }
}
- (void)regionBtnClick:(UIButton *)sender{
    EVTPhoneAreaCodeViewController *vc = [[EVTPhoneAreaCodeViewController alloc]init];
    vc.completion = ^(NSString *name, NSString *code){
        
        UIButton *b = sender;
        [b setTitle:[NSString stringWithFormat:@"%@",name] forState:UIControlStateNormal];
        _regionStr = name;
        _numberStr = code;
        NSMutableAttributedString *messageStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"+ %@",_numberStr] attributes:nil];
        [messageStr addAttribute:NSForegroundColorAttributeName value:ColorI(0x849195) range:NSMakeRange(0,messageStr.length)];
        [messageStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13] range:NSMakeRange(0,1)];
        [messageStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(1, messageStr.length-1)];
        self.numberLab.attributedText = messageStr;
    };
    [self.navigationController pushViewController:vc animated:YES];
    
}


@end
